﻿package com.reyco1.tool
{
	import com.reyco1.util.ValidateUtil;
	import com.reyco1.extension.DispatchExtension;
	import com.reyco1.events.FormEvent;
	
	public class FormValidator extends DispatchExtension
	{
		private var arrFields:Array;
		
		public function FormValidator():void
		{
			this.arrFields = new Array();
		}
		
		/**
		 * Adds a TextField or TextArea to the validation queue
		 * @param $textAreaOrField : TextArea or TextField to validate
		 * @param $validationType : Validation type. The validation type can be one of five:
		 *  
		 * <ul>
		 * <li>name</li>
		 * <li>email</li>
		 * <li>phone</li>
		 * <li>state</li>
		 * <li>zip</li>
		 * </ul>
		 * 
		 */		
		public function addToValidate($textAreaOrField:*, $validationType:String):void
		{
			this.arrFields.push({field:$textAreaOrField, type:$validationType, valid:false});
		}
		
		/**
		 * Starts the validation process. Once the validation is complete, a <b>FormEvent.VALIDATION_COMPLETE</b> is fired. This event carries
		 * a "params" object with a "result" value. The result value is an array of objects, each object contains three values:
		 *
		 * <ul>
		 * <li><b>field</b>: the text field or text area being validated</li>
		 * <li><b>type</b>: the validation type</li>
		 * <li><b>valid</b>: a boolean value specifying if the contents in the field are valid or not</li>
		 * </ul>
		 * 
		 * eventType : FormEvent.VALIDATION_COMPLETE
		 * 
		 * 
		 */		
		public function validate():void
		{
			for(var a:Number = 0; a<this.arrFields.length; a++){
				switch(this.arrFields[a].type.toLowerCase())
				{
					case "name":
					this.arrFields[a].valid = ValidateUtil.validName(this.arrFields[a].field.text);
					break;
					
					case "email":
					this.arrFields[a].valid = ValidateUtil.validEmail(this.arrFields[a].field.text);
					break;
					
					case "phone":
					this.arrFields[a].valid = ValidateUtil.validPhone(this.arrFields[a].field.text);
					break;
					
					case "state":
					this.arrFields[a].valid = ValidateUtil.validState(this.arrFields[a].field.text);
					break;
					
					case "zip":
					this.arrFields[a].valid = ValidateUtil.validZip(this.arrFields[a].field.text);
					break;
				}
			}
			this.dispatchEvent(new FormEvent(FormEvent.VALIDATION_COMPLETE, {result:this.arrFields}))
		}
	}
}